const Message = require("./modules/messageModule");
const { Op } = require("sequelize");

// 添加留言
const addMessage = async (info) => {
  const data = await Message.create(info, {
    attributes: ["id", "nickname", "content", "createDate", "avatar"],
  });
  return data.toJSON();
};

//删除留言
const deleteMessage = async (id) => {
  await Message.destroy({
    where: {
      id,
    },
  });
  return;
};

//分页获取留言
const getMessageList = async (page = 1, limit = 10, keyword = "") => {
  let where = {};
  if (keyword.replace(/\s*/g, "").length !== 0) {
    where = {
      [Op.or]: [
        { nickname: { [Op.like]: `%${keyword}%` } },
        { content: { [Op.like]: `%${keyword}%` } },
      ],
    };
  }
  where.blogId = null; //获取留言
  const { count, rows } = await Message.findAndCountAll({
    attributes: ["id", "nickname", "content", "createDate", "avatar"],
    where,
    offset: (page - 1) * limit,
    limit,
    order: [["createDate", "DESC"]], //按时间降序，排序
  });
  const data = JSON.parse(JSON.stringify(rows));
  return {
    total: count,
    rows: data,
  };
};

module.exports = {
  addMessage,
  deleteMessage,
  getMessageList,
};
